package br.org.group.android.net;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import android.util.Log;

public class FortuneParser {

	private static String TAG_ID = "ID";
	private static String TAG_MESSAGE = "MSG";
	private static String TAG_AUTHOR = "AUTOR";
	private static String TAG_CATEGORY = "CATEGORIA";

	private Integer id;
	private String message;
	private String author;
	private String category;

	public FortuneParser(String uri) throws Exception {
		try {
			id = 0;
			if (uri == null) {
				return;
			}

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(uri);
			doc.getDocumentElement().normalize();

			Element fortune = (Element) doc.getElementsByTagName("FORTUNE")
					.item(0);
			Element elementId = (Element) fortune.getElementsByTagName(TAG_ID)
					.item(0);
			Element elementMessage = (Element) fortune.getElementsByTagName(
					TAG_MESSAGE).item(0);
			Element elementAuthor = (Element) fortune.getElementsByTagName(
					TAG_AUTHOR).item(0);
			Element elementCategory = (Element) fortune.getElementsByTagName(
					TAG_CATEGORY).item(0);

			if (elementId.getChildNodes().item(0) != null) {
				this.id = Integer.parseInt(elementId.getChildNodes().item(0)
						.getNodeValue());
			}

			if (elementMessage.getChildNodes().item(0) != null) {
				this.message = elementMessage.getChildNodes().item(0)
						.getNodeValue();
			}

			// Setando "" no author caso não tenha esse valor no xml. Se estiver
			// null irá dar erro ao inserir no banco
			if (elementAuthor.getChildNodes().item(0) == null) {
				this.author = "";
			} else {
				this.author = elementAuthor.getChildNodes().item(0)
						.getNodeValue();
			}

			// Setando "" no category caso não tenha esse valor no xml. Se
			// estiver null irá dar erro ao inserir no banco
			if (elementCategory.getChildNodes().item(0) == null) {
				this.category = "";
			} else {
				this.category = elementCategory.getChildNodes().item(0)
						.getNodeValue();
			}

		} catch (Exception e) {
			URL url;
				url = new URL(uri);
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setRequestProperty("Request-Method", "GET");
				connection.setDoInput(true);
				connection.setDoOutput(false);
				connection.connect();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()),2048);
				// Lê a conexão
				StringBuffer newData = new StringBuffer();
				String s = "";
				while (null != ((s = br.readLine()))) {
					newData.append(s);
				}
				br.close();
				connection.disconnect();
				s = newData.toString();
				String[] s1 = s
						.replace(
								"<?xml version=\"1.0\" encoding=\"utf-8\" ?><FORTUNE><ID>",
								"").split("</ID>");
				this.id = Integer.parseInt(s1[0]);
				
				s1[1] = s1[1].replace("<MSG>", "");
				s1 = s1[1].split("</MSG>");
				this.message = s1[0];

				s1 = s1[1].replace("<AUTOR>", "").split("</AUTOR>");
				if (s1 != null && s1.length > 1) {
					this.author = s1[0];
				} else {
					this.author = "";
				}
				
				s1 = s1[1].replace("<CATEGORIA>", "").split("</CATEGORIA>");
				if (s1 != null && s1.length > 1) {
					this.category = s1[0];
				} else {
					this.category = "";
				}

		}
	}

	public String getAuthor() {
		return author;
	}

	public String getCategory() {
		return category;
	}

	public Integer getId() {
		return id;
	}

	public String getMessage() {
		return message;
	}
}